require([ 'jquery', 'common', 'validate','timepicker', 'pagination', 'bootstrap', 'dateZh','plupload','T_upload'], function($, common,validate,timepicker,T_upload) {
	
	//日期控件
	$('#date-start, #date-end').datetimepicker({
		format : "yyyy-mm-dd hh:ii:ss",
		language : "zh-CN",
		todayBtn : 1,
		autoclose : true,
		todayHighlight : true,
		forceParse : true,
		minuteStep : 10
	});
	
	var addForm = $('#addForm');
	var updateForm = $('#updateForm');
	
	var first_load = true;
	var reload = true; 
	
	//placeholder兼容ie start
	$(function() {
		if (!placeholderSupport()) { // 判断浏览器是否支持 placeholder
			$('[placeholder]').focus(function() {
				var input = $(this);
				if (input.val() == input.attr('placeholder')) {
					input.val('');
					input.removeClass('placeholder');
				}
			}).blur(function() {
				var input = $(this);
				if (input.val() == ''
						|| input.val() == input.attr('placeholder')) {
					input.addClass('placeholder');
					input.val(input.attr('placeholder'));
				}
			}).blur();
		};
		
		showOrderRefundByPage(1); 
	});
	function placeholderSupport() {
		return 'placeholder' in document.createElement('input');
	}
	//placeholder兼容ie end

	//清除按钮
	$('.clearBtn').on('click', function() {
		$('.setTableLength').val(10);
		$("#orderId").val(''),  
		$("select[name='supplierAuditStatus']").val(''),
		$("select[name='status']").val('')
	});
	
	$(".setTableLength").change(function() {
		reload = true;
		showOrderRefundByPage(1);
	});
	
	//处理供应商审核不通过的记录
	$(document).on('click', '.service-deal-btn', function (e) { 
        var $this = $(this),
        parentTr = $this.parents('tr'),
        id = $this.data('id'),
        orderId = $this.data('orderid'),
        pageno = parentTr.data('pageno'); 
        $.getJSON(ctx + '/order/aftersale/querybyid', {
    		id : id
    	}, function(data) {
    		var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
    		if(data==null || data.length <= 0){
    			$(".errorMsg").html("数据异常,请重试");
    		}else{
    			var sale = data.orderAftersale;   
    			$("#dealOrderAftersaleForm").find("input[name='id']").val(id);
    	        $("#dealOrderAftersaleForm").find("input[name='orderId']").val(sale.orderSn);
    	        $("#dealOrderAftersaleForm").find("input[name='amount']").val(sale.amount);
    	        $("#dealOrderAftersaleForm").find("input[name='supplierAuditAmount']").val(sale.supplierAuditAmount);
    	        $("#dealOrderAftersaleForm").find("input[name='remark']").val(sale.remark);
    	        $("#dealOrderAftersaleForm").find("input[name='supplierAuditOpinion']").val(sale.supplierAuditOpinion);
    	        if(sale.remark != null && sale.remark != "") {
    	        	$("#deal-img").attr("src", ctx + sale.proImg);
    	        } 
    		}
    	}); 
    });
	
	/** 审核通过start **/
	$("#btn_deal_audit").click(function() { 
		//审核状态，1待审核，2审核通过，3审核不通过 
		deal(); 
	});
	/**  审核通过end **/ 
		
	/**
	 * 客服处理售后订单
	 */
	function deal() {
		var id = $("#dealOrderAftersaleForm").find("input[name='id']").val();
		var finalAmount = $("#dealOrderAftersaleForm").find("input[name='finalAmount']").val(); 
		$.post(ctx+"/order/aftersale/deal", {
				id:id,
				finalAmount:finalAmount
		},function (data) {
			var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
			 if(result!=null && result=="againLogin") {
				 $('.commonConfirm').modal('hide');
				 common.alert1("登录过期，请重新登录");;
				 setTimeout("location.href = ctx + '/login.html'",1000);
		     }else if(result=='success'){ 
		  		 $(".modal-deal-aftersale").modal('hide');
		         common.mySuccessModal2('提交成功');
		         showOrderRefundByPage(1);
		  	}else{
		  		$(".errorMsg").html(data.message);
		  	}
		  },"json"); 
	}
	
	
	$(document).on('click', '.audit-btn', function (e) { 
        var $this = $(this),
        parentTr = $this.parents('tr'),
        id = $this.data('id'),
        orderId = $this.data('orderid'),
        pageno = parentTr.data('pageno');
        $(".errorMsg").html("");
        $("#auditOrderAftersaleForm").find("input[name='id']").val(id);
        $("#auditOrderAftersaleForm").find("input[name='orderId']").val(orderId);
        $("#auditOrderAftersaleForm").find("input[name='amount']").val("");
        $("#auditOrderAftersaleForm").find("input[name='serviceAuditOpinion']").val("");
    });
	
	/** 审核通过start **/
	$("#btn_audit_pass").click(function() { 
		//审核状态，1待审核，2审核通过，3审核不通过 
		audit(2); 
	});
	/**  审核通过end **/

	/** 审核不通过start **/
	$("#btn_audit_notpass").click(function() { 
		//审核状态，1待审核，2审核通过，3审核不通过 
		audit(3);
	});
	/**  审核通过end **/
		
	/**
	 * 客服审核售后订单
	 */
	function audit(auditStatus) {
		var id = $("#auditOrderAftersaleForm").find("input[name='id']").val();
		var serviceAuditOpinion = $("#auditOrderAftersaleForm").find("input[name='serviceAuditOpinion']").val(); 
		var amount = $("#auditOrderAftersaleForm").find("input[name='amount']").val(); 
		$.post(ctx+"/order/aftersale/serviceaudit", {
				id:id,
				serviceAuditStatus:auditStatus,
				serviceAuditOpinion:serviceAuditOpinion,
				amount:amount
		},function (data) {
			var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
			 if(result!=null && result=="againLogin") {
				 $('.commonConfirm').modal('hide');
				 common.alert1("登录过期，请重新登录");;
				 setTimeout("location.href = ctx + '/login.html'",1000);
		     }else if(result=='success'){ 
		  		 $(".modal-audit-aftersale").modal('hide');
		         common.mySuccessModal2('提交成功');
		         showOrderRefundByPage(1);
		  	}else{
		  		$(".errorMsg").html(data.message);
		  	}
		  },"json"); 
	}
	
	
	$(document).on('click', '#reset-amount', function (e) {
		$("#supplier-audit-amount-div").show();
	});
	
	
	//供应商处理售后订单
	$(document).on('click', '.supplir-audit-btn', function (e) { 
        var $this = $(this),
        parentTr = $this.parents('tr'),
        id = $this.data('id'),
        orderId = $this.data('orderid'),
        pageno = parentTr.data('pageno'); 
        $.getJSON(ctx + '/order/aftersale/querybyid', {
    		id : id
    	}, function(data) {
    		var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
    		if(data==null || data.length <= 0){
    			$(".errorMsg").html("数据异常,请重试");
    		}else{
    			var sale = data.orderAftersale;   
    			$("#supplierAuditOrderAftersaleForm").find("input[name='id']").val(id);
    	        $("#supplierAuditOrderAftersaleForm").find("input[name='orderId']").val(sale.orderSn);
    	        $("#supplierAuditOrderAftersaleForm").find("input[name='amount']").val(sale.amount);
    	        $("#supplierAuditOrderAftersaleForm").find("input[name='supplierAuditAmount']").val(sale.amount);
    	        $("#supplierAuditOrderAftersaleForm").find("input[name='remark']").val(sale.remark);
    	        if(sale.remark != null && sale.remark != "") {
    	        	$("#supplier-audit-img").attr("src", ctx + sale.proImg);
    	        }
    	        
    		}
    	});
        
    }); 

	/** 审核不通过start **/
	$("#btn_supplier_audit").click(function() { 
		//审核状态，1待审核，2审核通过，3审核不通过 
		supplierAudit();
	});
	/**  审核通过end **/
		
	/**
	 * 客服审核售后订单
	 */
	function supplierAudit() {
		var id = $("#supplierAuditOrderAftersaleForm").find("input[name='id']").val();
		var supplierAuditOpinion = $("#supplierAuditOrderAftersaleForm").find("input[name='supplierAuditOpinion']").val(); 
		var supplierAuditAmount = $("#supplierAuditOrderAftersaleForm").find("input[name='supplierAuditAmount']").val(); 
		$.post(ctx+"/order/aftersale/supplieraudit", {
			id:id, 
			supplierAuditOpinion:supplierAuditOpinion,
			supplierAuditAmount:supplierAuditAmount
		},function (data) {
			var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
			 if(result!=null && result=="againLogin") {
				 $('.commonConfirm').modal('hide');
				 common.alert1("登录过期，请重新登录");;
				 setTimeout("location.href = ctx + '/login.html'",1000);
		     }else if(result=='success'){ 
		  		 $(".modal-supplier-audit-aftersale").modal('hide');
		         common.mySuccessModal2('提交成功');
		         showOrderRefundByPage(1);
		  	}else{
		  		$(".errorMsg").html(data.message);
		  	}
		  },"json"); 
	}
	

	$(".searchBtn").click(function() {
		reload = true;
		showOrderRefundByPage(1);
	});
	
	/** 列表查询start **/
	function showOrderRefundByPage(pageNum) {
		if ($(".all").is(':checked')) {
			$(".all").removeAttr('checked');								
		}	
		if($('.alert-warning').length>0){
    		$('.alert-warning').remove();
    	}
		$.getJSON(ctx + '/order/aftersale/showbypage', {	
				pageNum : pageNum,
				pageSize : $('.setTableLength').val() || 10, 
				orderId : $("#orderId").val(), 
				serviceAuditStatus : $("select[name='serviceAuditStatus']").val(),
				status : $("select[name='status']").val()
			},
			function(data){  
				if($('.loading')){
					$('.loading').remove();
				}
				var result = data.result;
				if(result!=null && result=="noauthority") {
					common.alert1('你无此权限!');
					return;
				}
				if(data.result!=null && data.result=="againLogin") {
					common.alert1("登录过期，请重新登录");
						setTimeout("location.href = ctx + '/login.html'",1000);
       			} else if(data.result.length == 0) { 
					$('.table-responsive').append('<div class="alert alert-warning no-result text-center" role="alert">没有找到记录 </div>');
                } else{
                	var isInterior = $("#isInterior").val();
       				var datapage = data.result;
					var datalist = datapage.result;
					var totalCount = datapage.totalCount;
					var pageNum = datapage.pageNo;
					var pageSize = datapage.pageSize;
					var totalPages = datapage.totalPages;
					$(".totalCount").html(totalCount);
					$(".totalPages").html(totalPages);
					$(".pageNo").html(pageNum);
                    var tempHtml="";   
                    var ser = 1;
                    for(var i=0;i<datalist.length;i++){   
                    	var data = datalist[i]; 
                    	var no = (pageNum-1)*pageSize+i+1; 
                    	tempHtml +="<tr data-id='"+data.id+"' data-pageno='" + pageNum + "'>";
                    	tempHtml +="<td>"+ser+"</td>"; 
                    	tempHtml +="<td>"+isnull(data.orderSn)+"</td>"; 
                    	tempHtml +="<td>"+status(data.status)+"</td>";  
                    	tempHtml +="<td>"+causeType(data.causeType)+"</td>";
                    	tempHtml +="<td>"+isnull(data.remark)+"</td>"; 
                    	tempHtml +="<td>"+common.getSmpFormatDate(data.createTime)+"</td>"; 
                    	tempHtml +="<td>"+serviceAuditStatus(data.serviceAuditStatus)+"</td>"; 
                    	tempHtml +="<td>"+supplierAuditStatus(data.supplierAuditStatus)+"</td>";  
                    	ser = ser + 1;
                    	tempHtml +="<td>";
                    	tempHtml +="<button type='button' data-toggle='modal' data-target='.modal-edityd' data-id="+data.id+" onclick='queryDetail(" +data.orderId+")' class='btn btn-primary btn-xs detail-btn'>查看</button>&nbsp;";
                    	
                    	if(isInterior == 1) {
                    		/*审核状态，1待审核，2审核通过，3审核不通过*/
                    		if(data.serviceAuditStatus == 1){
                    			//平台方审核
                        		tempHtml +="<button type='button' data-toggle='modal' data-target='.modal-audit-aftersale' data-id="+data.id+" data-orderid="+data.orderSn+" class='btn btn-success btn-xs audit-btn'>审核</button>";
                        	}
                    		
                    		//处理供应商审核不通过的记录
                    		if(data.supplierAuditStatus == 3){
                    			//平台方审核
                        		tempHtml +="<button type='button' data-toggle='modal' data-target='.modal-deal-aftersale' data-id="+data.id+" data-orderid="+data.orderSn+" class='btn btn-warning btn-xs service-deal-btn'>处理</button>";
                        	}
                    	}
                    	
                    	if(isInterior == 0) {
                    		/*审核状态，1待审核，2审核通过，3审核不通过*/
                    		if(data.serviceAuditStatus == 2 && data.supplierAuditStatus == 1){
                    			//平台方审核通过后供应商审核
                        		tempHtml +="<button type='button' data-toggle='modal' data-target='.modal-supplier-audit-aftersale' data-id="+data.id+" data-orderid="+data.orderSn+" class='btn btn-success btn-xs supplir-audit-btn'>处理</button>";
                        	}
                    	}
                    	
                    	tempHtml +="</td>";
                    	tempHtml +="</tr>";
                    	if($('.alert-warning').length>0){
                    		$('.alert-warning').remove();
                    	}
                    }   
                    if(datalist.length === 0&&$('.alert-warning').length<=0) { 
						$('.table-responsive').append('<div class="alert alert-warning no-result text-center" role="alert">没有找到记录 </div>');
	                } 
                    $('#dataBody').html(tempHtml);
                   
                    if (reload) {
                    	reload = false;
                    	first_load = true;
    					var initPagination = function() {
    						$("#Pagination").pagination(totalCount, {
    							num_edge_entries : 1, // 边缘页数
    							num_display_entries : 4, // 主体页数
    							callback: pageselectCallback,
    							prev_text : "«",
    							next_text : "»",
    							items_per_page : pageSize, 
    							link_to : 'javascript:void(0);'
    						});
    					}();
    					/**分页e**/
                    }
				} 
			}).fail(function (err) { 
				if($('.loading')){
					$('.loading').remove();
				}
				common.alert('服务器错误！请刷新页面重试或联系管理员',"确定"); 
            });  
	}
	
	function pageselectCallback(page_index, jq) {
		if (first_load) { //第一次初始化不需要请求
			first_load = false;
			return false;
		}
		pageNum = page_index + 1;
		showOrderRefundByPage(pageNum);
	}
	/** 列表查询end **/ 
	
	function isnull(value) {
		if (value == null || value == '' || typeof (value) == "undefined")
			return "--";
		else
			return value;
	}
	
	
	/*售后状态，1未处理，2处理中，3已完成*/
	function status(value) {
		if (value == null || value == ''){
			return "未知";
		}else if(value == 1) {
			return "未处理";
		}else if(value == 2) {
			return "处理中";
		}else if(value == 3) {
			return "已完成";
		}
	}
	
	/*售后原因，1错发/漏发，2拒签退回，3丢件，4瘪罐，99其他*/
	function causeType(value) {
		if (value == null || value == ''){
			return "未知";
		}else if(value == 1) {
			return "错发/漏发";
		}else if(value == 2) {
			return "拒签退回";
		}else if(value == 3) {
			return "丢件";
		}else if(value == 4) {
			return "瘪罐";
		}else if(value == 499) {
			return "其他";
		}else{
			return "无";
		}
	}

	/* 客服审核状态，1待审核，2审核通过，3审核不通过*/
	function serviceAuditStatus(value) {
		if (value == null || value == ''){
			return "未知";
		}else if(value == 1) {
			return "待审核";
		}else if(value == 2) {
			return "审核通过";
		}else if(value == 3) {
			return "审核不通过";
		}
	}
	
	/*物流审核状态，1待审核，2审核通过，3审核不通过*/
	function supplierAuditStatus(value) {
		if (value == null || value == ''){
			return "未知";
		}else if(value == 1) {
			return "待审核";
		}else if(value == 2) {
			return "审核通过";
		}else if(value == 3) {
			return "审核不通过";
		}
	}
	
	function isnumber(value) {
		if (value == null || value == '')
			return "0.00";
		else
			return value;
	}
	
});


function queryDetail(id){ 
	$.getJSON(ctx + '/order/showorderinfo', {
		id : id
	}, function(data) {
		var order = data.order;
		var productList = data.orderProductList;
		if(data != null){ 
			$(".modal-edityd").find("input[name='id']").val(order.id);
			$(".modal-edityd").find("input[name='orderId']").val(order.orderId);
			$(".modal-edityd").find("select[name='tradeType']").val(order.tradeType);
			$(".modal-edityd").find("input[name='status']").val(order.status);
			$(".modal-edityd").find("input[name='createTime']").val(getFormatDate(order.createTime));
			$(".modal-edityd").find("input[name='paymentTime']").val(getFormatDate(order.paymentTime));
			$(".modal-edityd").find("select[name='paymentType']").val(order.paymentType);
			$(".modal-edityd").find("input[name='receiver']").val(order.receiver);
			$(".modal-edityd").find("input[name='receiverMobile']").val(order.receiverMobile);
			$(".modal-edityd").find("input[name='receiverIdnumber']").val(order.receiverIdnumber);
			$(".modal-edityd").find("input[name='receiverPcdt']").val(order.receiverPcdt);
			$(".modal-edityd").find("input[name='logisticsName']").val(order.logisticsName);
			$(".modal-edityd").find("input[name='logisticsNumber']").val(order.logisticsNumber);
			$(".modal-edityd").find("input[name='deliveryTime']").val(getFormatDate(order.deliveryTime));
			$(".modal-edityd").find("input[name='orderRemark']").val(order.orderRemark);
			$(".modal-edityd").find("input[name='merchantRemark']").val(order.merchantRemark); 
			
			var tempHtml = "";
			var productTotal = 0;
			for(var i=0;i<productList.length;i++){   
            	var product = productList[i]; 
            	var unitPriceTemp = 0;
            	if(product.unitPrice != null){
            		unitPriceTemp = product.unitPrice;
            	}
            	tempHtml +="<tr>";  
            	tempHtml +="<td>"+(product.code)+"</td>";
            	tempHtml +="<td>"+(product.productName)+"</td>";
            	tempHtml +="<td>"+(product.dateValue)+"</td>"; 
            	tempHtml +="<td>"+(product.num)+"</td>";
            	tempHtml +="<td>"+(product.specificationNumber) +  product.packType + "装</td>";
            	tempHtml +="<td>￥"+(unitPriceTemp).toFixed(2);+"</td>";
            	tempHtml +="<td>￥"+(unitPriceTemp * product.num).toFixed(2);+"</td>"; 
        		tempHtml +="</tr>";  
        		productTotal += (unitPriceTemp * product.num);
            }   
			tempHtml +="<tr><td></td><td></td><td></td><td></td><td></td><td colspan='2'>供货价总计：￥"+productTotal.toFixed(2)+"</td></tr>";
			tempHtml +="<tr><td></td><td></td><td></td><td></td><td></td><td colspan='2'>运费：￥"+(order.freight).toFixed(2)+"</td></tr>";
			/*tempHtml +="<tr><td></td><td></td><td></td><td></td><td></td><td colspan='2'>订单金额：￥"+(order.orderAmount).toFixed(2)+"</td></tr>";*/
			
			$('#orderDetailDataBody').html(tempHtml); 
		}else{
			alert("查询失败");
		}
	});
}
function auditStatus(value) {
	if (value == null || value == ''){
		return "未知";
	}else if(value == 1) {
		return "待审核";
	}else if(value == 2) {
		return "审核通过";
	}else if(value == 3) {
		return "审核不通过";
	}
}

/** 转换时间start **/
function getFormatDate(time){
	if(time==null || time=="") {
		return "--";
	}
	var t = new Date(time);
	var tf = function(i){
		return (i < 10 ? '0' : '') + i
	};
	return "yyyy-MM-dd HH:mm:ss".replace(/yyyy|MM|dd|HH|mm|ss/g, function(a){
		switch(a){
			case 'yyyy':
				return tf(t.getFullYear());
				break;
			case 'MM':
				return tf(t.getMonth() + 1);
				break;
			case 'mm':
				return tf(t.getMinutes());
				break;
			case 'dd':
				return tf(t.getDate());
				break;
			case 'HH':
				return tf(t.getHours());
				break;
			case 'ss':
				return tf(t.getSeconds());
				break;
		};
	});
};